<?php

namespace controller;

require_once('/model/Loginmodel.php');
require_once('/view/UserInfo.php');
require_once('/view/Loginview.php');
require_once('/view/HTMLView.php');

	class userLogin {

		/**
		 * @var $usrInfoView UserInfo objekt.
		 * @var $loginM Loginmodel objekt.
		 * @var $loginView Loginview objekt.
		 * @var $pageView HTMLView objekt.
		 * @var $arrayusername string.
		 * @var $arraypassword string.
		 */
		private $usrInfoView;
		private $loginM;
		private $loginView;
		private $pageView;
		private static $arrayusername = "username";
		private static $arraypassword = "password";

		function __construct() {
			$this->usrInfoView = new \view\UserInfo();
			$this->loginM = new \model\Loginmodel();
			$this->loginView = new \view\Loginview();
			$this->pageView = new \view\HTMLView();
		}

		/**
		 * @return string med html kod
		 * En funktion som loggar in eller loggar ut användaren.
		 */
		public function loginUser() {
			if($this->loginView->getLogoutInfo()) {
				return $this->logoutUser();
			}
			else if($this->usrInfoView->cookieIsset()) {
				if($this->loginM->loginUserWithCookie()) {
					$this->pageView->setLogginInfo("Inloggning lyckades via cookies");
					return $this->pageView->getMemberPage();
				}
				else {
					$this->pageView->setLogginInfo("Felaktig information i cookie");
				}
			}
			else if($this->usrInfoView->sessionSet()) {
				return $this->pageView->getMemberPage();
			}
			else if($this->usrInfoView->serverRequestMethod() == "POST") {
				$loggInfo = "";
				try {
					$userInfo = $this->usrInfoView->getUserInfo();
					$this->loginM->validateUsrInfo(
													$userInfo[self::$arrayusername],
													$userInfo[self::$arraypassword]);
				}
				catch (\Exception $e) {
					$loggInfo = $e->getMessage();
				}
				if($loggInfo == "") {
					if($this->usrInfoView->getRememberData()) {
						$this->saveUser();
						$this->pageView->setLogginInfo("
							Inloggning lyckades och vi kommer ihåg dig nästa gång");
					}
					else {
						$this->pageView->setLogginInfo("Inloggning lyckades");
					}
					return $this->pageView->getMemberPage();
				}
				else {
					$this->pageView->setLogginInfo($loggInfo);
					$this->pageView->setInputValue($_POST["uName"]);
					return $this->pageView->getLoginPage();
				}
			}
			return $this->pageView->getLoginPage();
		}

		/**
		 * @return string med html kod
		 * Funktion som tar bort alla cookies och loggar ut användaren.
		 */
		public function logoutUser() {
			$this->loginM->removeUsr();
			session_destroy();
			$this->pageView->setLogginInfo("Du har nu loggat ut");
			return $this->pageView->getLoginPage();
		}

		public function saveUser() {
			$userInfo = $this->usrInfoView->getUserInfo();
			$this->loginM->saveUsrInfo($userInfo[self::$arrayusername],
									   $userInfo[self::$arraypassword]);
		}
	}
?>